import { useState, useRef, useEffect } from "react";
import { Tooltip, Space, Button, Popconfirm, message, Modal } from "antd";
import {
  PauseCircleOutlined,
  CaretRightOutlined,
  DeleteOutlined,
  StopOutlined,
  InfoCircleOutlined,
  MoreOutlined
} from "@ant-design/icons";
import useProcessDefOptionsHooks from "./ProcessDefOptionsHooks.jsx";
import CamundaAPI from "@/api/CamundaApi.js";

import useModalHooks from "./ModalHooks";

function useTaskList() {
  // loading
  const [loading, setLoading] = useState(false);
  // 表格数据
  const [tableData, setTableData] = useState({
    list: [], // 数据列表
  });

  // 搜索关键字
  const [keyWords, setKeyWords] = useState("");
  const [procDefId, setProcDefId] = useState("");
  // 排序信息 TODO
  const sortData = useRef({
    sortField: "task.create_time_",
    sortOrder: "descend",
  });

  // 分页数据 - 用于同步计算
  const paginationData = useRef({
    current: 1, // 当前页数
    pageSize: 10, // 页面显示的条目数
    total: 0, // 记录条目总数
    pageSizeOptions: [5, 10, 15, 20, 30, 50, 100], // 条目数选项
  });

  const columnRender = (v) => {
    return (
      <Tooltip placement="topLeft" title={v}>
        {v}
      </Tooltip>
    );
  };

  // 表格字段
  const columnsData = useRef([
    {
      title: "Task Name",
      dataIndex: "taskName",
      key: "task.name_",
      width: 150,
      fixed: "left",
      sorter: true,
      ellipsis: {
        showTitle: false,
      },
      render: columnRender,
    },
    {
      title: "Task Id",
      dataIndex: "taskId",
      key: "task.id_",
      fixed: "left",
      width: 200,
      sorter: true,
      ellipsis: {
        showTitle: false,
      },
      render: columnRender,
    },
    {
      title: "Defined Name",
      dataIndex: "taskDefKey",
      key: "task.task_def_key_",
      fixed: "left",
      width: 100,
      sorter: true,
      ellipsis: {
        showTitle: false,
      },
      render: columnRender,
    },

    {
      title: "Assignee",
      dataIndex: "taskAssignee",
      key: "task.assignee_",
      fixed: "left",
      width: 100,
      sorter: true,
      ellipsis: {
        showTitle: false,
      },
      render: columnRender,
    },
    {
      title: "Owner",
      dataIndex: "taskOwner",
      key: "task.owner_",
      fixed: "left",
      width: 100,
      sorter: true,
      ellipsis: {
        showTitle: false,
      },
      render: columnRender,
    },

    {
      title: "DefKey",
      dataIndex: "defKey",
      key: "def.key_",
      fixed: "left",
      width: 200,
      sorter: true,
      ellipsis: {
        showTitle: false,
      },
      render: columnRender,
    },
    {
      title: "DefName",
      dataIndex: "defName",
      key: "def.name_",
      width: 150,
      sorter: true,
      ellipsis: {
        showTitle: false,
      },
      render: columnRender,
    },
    {
      title: "DefVersion",
      dataIndex: "defVersion",
      key: "def.version_",
      width: 150,
      sorter: true,
      ellipsis: {
        showTitle: false,
      },
      render: columnRender,
    },
    {
      title: "Business Key",
      dataIndex: "businessKey",
      key: "procinst.business_key_",
      width: 150,
      fixed: "left",
      sorter: true,
      ellipsis: {
        showTitle: false,
      },
      render: columnRender,
    },
    {
      title: "Process Instance Id",
      dataIndex: "processInstanceId",
      key: "procinst.id_",
      fixed: "left",
      width: 200,
      sorter: true,
      ellipsis: {
        showTitle: false,
      },
      render: columnRender,
    },
    {
      title: "Operate",
      dataIndex: "operate",
      key: "operate",
      fixed: "right",
      align: "center",
      width: 180,
      render: (text, record) => {
        return (
          <div>
            <Space>
              <Button
                type="dashed"
                icon={<InfoCircleOutlined />}
                onClick={() => {
                  setTaskId(record.taskId);
                  openModalForTaskInfo();
                }}
              ></Button>

              <Button
                type="primary"
                size="small"
                icon={<CaretRightOutlined />}
                onClick={() => {
                  setTaskId(record.taskId);
                  openModalForCompleteTask();
                }}
              ></Button>


<Button
                type="dashed"
                icon={<MoreOutlined />}
                onClick={() => {
                  setProcInstId(record.processInstanceId);
                  openModalForProcInst();
                }}
              ></Button>

            </Space>
          </div>
        );
      },
    },
  ]);

  // 搜索数据
  const search = function (clearPage) {
    // 初始化字段排序信息
    initColumnSortInfo();
    // 打开loading
    setLoading(true);

    // 清除分页
    if (clearPage) {
      paginationData.current.current = 1;
    }

    // 创建处理分页和排序
    let params = {
      keyWords,
      procDefId,
      current: paginationData.current.current,
      pageSize: paginationData.current.pageSize,
    };

    if (sortData.current.sortOrder) {
      params = {
        ...params,
        sortField: sortData.current.sortField,
        sortOrder: sortData.current.sortOrder.replace("end", ""),
      };
    }

    console.log("search:", params);

    CamundaAPI.queryTaskPage(params)
      .then((r) => {
        console.log(r);

        // 设置记录总数
        paginationData.current = {
          ...paginationData.current,
          total: r.result.total,
        };

        // 排序显示
        columnsData.current;

        // 设置数据列表内容
        setTableData({
          ...tableData,
          list: r.result.list,
        });

        // 关闭loading
        setLoading(false);
      })
      .catch(() => {
        // 关闭loading
        setLoading(false);
      });
  };

  // 初始化字段的排序信息 sortField:字段名   sortOrder:排序(ascend,descend,undefined)
  function initColumnSortInfo() {
    columnsData.current.forEach((item) => {
      delete item.sortOrder;
      if (sortData.current.sortOrder) {
        if (item.key === sortData.current.sortField) {
          item.sortOrder = sortData.current.sortOrder;
        }
      }
    });
  }

  const onPaginationChange = function (page, pageSize) {
    console.log(`pageChange[currentPage:${page},pageSize:${pageSize}]`);
    paginationData.current = {
      ...paginationData.current,
      current: page,
      pageSize,
    };
    // 查询数据
    search();
  };

  const onTableChange = function (pagination, filters, sorter) {
    console.log("sortChange", sorter);

    if (sorter.column) {
      sortData.current = {
        ...sortData.current,
        sortField: sorter.column.key,
        sortOrder: sorter.order,
      };
    } else {
      sortData.current = {
        ...sortData.current,
        sortOrder: "",
      };
    }
    search();
  };

  // onComponentDidMounted
  useEffect(() => {
    search();
  }, []);

  const { processDefList, onProcessDefSearch } = useProcessDefOptionsHooks();

  // ========================== 任务详情modal ============================

  const {
    modalVisible: modalVisibleForTaskInfo,
    setModalVisible: setModalVisibleForTaskInfo,
    openModal: openModalForTaskInfo,
    closeModal: closeModalForTaskInfo,
  } = useModalHooks();
  // ========================== 下一步modal ============================
  const {
    modalVisible: modalVisibleForCompleteTask,
    setModalVisible: setModalVisibleForCompleteTask,
    openModal: openModalForCompleteTask,
    closeModal: closeModalForCompleteTask,
  } = useModalHooks();

    // ========================== 流程实例详情modal ============================

    const {
      modalVisible: modalVisibleForProcInst,
      setModalVisible: setModalVisibleForProcInst,
      openModal: openModalForProcInst,
      closeModal: closeModalForProcInst,
    } = useModalHooks();

  // ========================== taskId ==================================

  const [taskId, setTaskId] = useState("");

    // ========================== procInstId ==================================

    const [procInstId, setProcInstId] = useState("");
  return {
    taskId,
    setTaskId,
    modalVisibleForTaskInfo,
    setModalVisibleForTaskInfo,
    openModalForTaskInfo,
    closeModalForTaskInfo,


    modalVisibleForCompleteTask,
    closeModalForCompleteTask,

    modalVisibleForProcInst,
    closeModalForProcInst,

    setKeyWords,
    loading,
    setLoading,
    tableData,
    paginationData,
    search,
    onPaginationChange,
    onTableChange,
    columnsData,

    processDefList,
    onProcessDefSearch,
    setProcDefId,
    procInstId
  };
}

export default useTaskList;
